package com.jingxi.common.multi;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Random;

public class ImageUtils {

    // 生成验证码图片的二进制数据
    public static byte[] burstCaptcha(String captchaText) throws IOException, IOException {
        // 设置图片宽高
        int width = 160;
        int height = 40;

        // 创建图像缓冲区
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics = image.createGraphics();

        // 设置背景颜色
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, width, height);

        // 设置字体
        Font font = new Font("Arial", Font.PLAIN, 30);
        graphics.setFont(font);

        // 设置干扰线
        Random random = new Random();
        graphics.setColor(Color.GRAY);
        for (int i = 0; i < 5; i++) {
            int x1 = random.nextInt(width);
            int y1 = random.nextInt(height);
            int x2 = random.nextInt(width);
            int y2 = random.nextInt(height);
            graphics.drawLine(x1, y1, x2, y2);
        }

        // 绘制验证码文本
        graphics.setColor(Color.BLACK);
        graphics.drawString(captchaText, 20, 30);

        // 释放资源
        graphics.dispose();

        // 将图像转换为字节数组
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "png", byteArrayOutputStream);
        return byteArrayOutputStream.toByteArray();
    }

    public static void burstQr(String source, OutputStream outputStream){
        //http://127.0.0.1:9002/base/code/qrCheck?uuid=7489384
        InetAddress localHost = null;
        try {
            localHost = Inet4Address.getLocalHost();
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        }
        String hostAddress = localHost.getHostAddress();
        String redirectUrl = String.format(
                "http://%s:%s/base/code/qrCheck?uuid=%s&ok=true"//ok=true暂时强制登录
                , hostAddress
                , "9002"
                , source
        );
        QrConfig qrConfig = new QrConfig(300, 300);
        QrCodeUtil.generate(redirectUrl, qrConfig,"png",outputStream);
    }

}
